<template>
  <div class="main-context">
    <t-table
      row-key="id"
      :data="data"
      :columns="columns"
      :bordered="true"
      hover
      :pagination="pagination"
      show-header
      cell-empty-content="-"
      :loading="loading"
    >
      <template #title-slot-name>
        <div style="display: flex; justify-content: space-between; align-items: center">
          操作
          <t-button size="small" @click="visible = true" v-permiss="'新增电影'">新增</t-button>
        </div>
      </template>
      <template #operation="{ row }">
        <t-popconfirm content="确认删除吗" @confirm="remove(row.id)">
          <t-button variant="text" theme="danger" size="small"><t-icon name="delete"></t-icon></t-button>
        </t-popconfirm>
      </template>
    </t-table>
    <t-dialog v-model:visible="visible" @confirm="add">
      <t-form style="width:380px" :rules="rules" ref="form" :data="formData" @submit="submit">
        <t-form-item label="名称" name="name">
          <t-input v-model="formData.name" placeholder="请输入地区名称" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { getMovieAreaList, movieAreaAdd, movieAreaRemove } from '@/api/movie'
import { MessagePlugin } from 'tdesign-vue-next'
import { usePageOption } from '../../hook'
const { pagination } = usePageOption()

// 获取列表数据
const loading = ref(false)
const data = ref([])
loading.value = true
getList()
function getList () {
  getMovieAreaList().then(res => {
    pagination.total = res.total
    data.value = res.data
    loading.value = false
  })
}
// 表格头部和单元格配置
const columns = ref([
  { colKey: 'id', title: '编号', minWidth: 200, width: 260 },
  { colKey: 'name', title: '地区', width: '200' },
  { colKey: 'count', title: '影片数量', width: '200' },
  { colKey: 'createTime', title: '创建时间', width: 180 },
  { colKey: 'operation', title: 'title-slot-name', width: 130 }
])
// 删除
function remove (id) {
  movieAreaRemove({ id }).then(res => {
    getList()
    MessagePlugin.success({
      content: '删除成功',
      duration: 2000
    })
  }).catch(err => {
    MessagePlugin.error(err.msg)
  })
}

const visible = ref(false)
const formData = reactive({
  name: ''
})
const rules = {
  name: [{ required: true }]
}
const form = ref(null)
function add (e) {
  form.value.submit()
}
function submit ({ validateResult }) {
  if (validateResult === true) {
    movieAreaAdd(formData).then(res => {
      getList()
      MessagePlugin.success(res.msg)
    }).catch(err => {
      MessagePlugin.error(err.msg)
    })
  }
}
</script>
<style scoped>
</style>
